import store from "@/store/index"
import PATH from "@/config/path.js"
let isDownLoadNum = 0
let isDownLoading = false
let waiting = undefined
let that = {}

function upDateModal() {
	uni.showModal({
		title: "发现新版本",
		content: "确认下载更新",
		showCancel: false,
		success: (res) => {
			if (res.confirm) { //当用户确定更新，执行更新
				doUpData();
			} else if (res.cancel) {
				// console.log('用户点击取消');
			}
		}
	})
}

function doUpData() {
	// waiting = plus.nativeUI.showWaiting("正在准备下载.....")
	uni.request({
		url: `${PATH.BASE_URL}rest/AppVersion/appVersion`,
		success: (res) => {
			const obj = res.data.result
			if (res.data.status === 1 && res.data.success) {
				that.popupShow = true
				that.popupText = `准备下载...`
				const downloadTask = uni.downloadFile({ //执行下载 
					url: obj.appDownloadUrl,
					success: downloadResult => { //下载成功
						if (downloadResult.statusCode === 200) {
							plus.runtime.install(downloadResult.tempFilePath, {
								force: false
							}, () => {
								that.popupText = `更新成功`
								// waiting.setTitle("更新成功")
								plus.runtime.restart();
							}, err => {
								that.popupText = `更新失败`
								// waiting.setTitle("更新失败")
							});
						} else {
							that.popupText = `更新失败`
							// waiting.setTitle("更新失败")
						}
					},
					complete: () => {
						waiting.close()
					}
				});
				downloadTask.onProgressUpdate(res => {
					if (isDownLoadNum === res.progress) return
					isDownLoadNum = res.progress
					console.log(isDownLoadNum, '-----', typeof(isDownLoadNum))
					if (isDownLoadNum) {
						that.popupText = `已下载${String(isDownLoadNum)}%了`

					}
				})
			} else {
				uni.showToast({
					title: '获取版本号接口异常!',
					icon: "none",
					mask: true
				})
			}
		}
	})

}

function mxGetDictMap(dictName, name) {
	let dictList = store.state.dictionary.dictMap[dictName] || []
	if (arguments.length === 2) {
		let obj = dictList.find(item => item.name == name)
		return (obj && obj.code) || ''
	} else {
		// console.log("mxGetDictMap",dictList)
		return dictList
	}
}
export function appHotUpdate(obj) {
	that = obj
	let version = null
	// console.log(`${PATH.BASE_URL}rest/AppVersion/appVersion`,'---路径');
	console.log(`${PATH.BASE_URL}rest/AppVersion/appVersion`);
	uni.request({
		url: `${PATH.BASE_URL}rest/AppVersion/appVersion`,
		success: (res) => {
			const obj = res.data.result
			if (res.data.status === 1 && res.data.success) {
				version = res.data.result.appVersionName
				plus.nativeUI.closeWaiting();
				if (plus.runtime.version !== version) {
					that.popupShow = false
					console.log("版本号不一致", isDownLoading)
					if (isDownLoading) return
					isDownLoading = true
					isDownLoadNum = 0
					upDateModal()
				}
			} else {
				uni.showToast({
					title: '获取版本号失败!',
					icon: "none",
					mask: true
				})
			}

		}
	})

}